package com.example.javabasic.thread.classtwo.threadpermessage.demo3;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AppServer extends Thread{

    private int port ;
    private static final int DEFAULT_PORT = 12222;
    private volatile boolean start = true;
    private List<ClientHandler> clientHandlers = new ArrayList<>();
    private final  ExecutorService exector = Executors.newFixedThreadPool(10);
    private ServerSocket server;

    public AppServer(){
        this(DEFAULT_PORT);
    }

    public AppServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {

        try {
            this.server = new ServerSocket(port);
            while(start){
                Socket client = server.accept();
                ClientHandler clientHandler = new ClientHandler(client);
                this.exector.submit(clientHandler);
                this.clientHandlers.add(clientHandler);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            this.destroies();
        }
    }
    //销毁
    public void destroies(){
        this.clientHandlers.stream().forEach(ClientHandler::stop);
        this.exector.shutdown();

    }
    //关闭
    public void shutDown(){
        this.start = false;
        this.interrupt();
        try {
            this.server.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
